#include <iostream>
#include "log.hpp"
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

void Useag(char *argv)
{
    cout << "you should input like this:" << argv << " a.b.c.d(Ip)" << " xxxx(port)" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Useag(argv[0]);
        exit(0);
    }
    uint16_t serverport = stoi(argv[2]);
    string serverip = argv[1];

    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_aton(serverip.c_str(), &server.sin_addr);
    while (1)
    {
        int cnt = 5;
        bool isreconnect = false;
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            return 1;
        }
        do
        {
            int n = connect(sockfd, (sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isreconnect = true;
                cnt--;
                std::cerr << "connect error..., reconnect: " << cnt + 1 << std::endl;
                sleep(2);
            }
            else
                break;
        } while (cnt && isreconnect);
        if (cnt == 0)
        {
            std::cerr << "user offline..." << std::endl;
            break;
        }

        //走到这里说明链接成功
        string messages;
        cout<<"Please Enter# ";
        getline(cin,messages);

        ssize_t n=write(sockfd,messages.c_str(),messages.size());
        if(n<0)
        {
            std::cerr<<"Write Error"<<std::endl;
        }

        char inbuffer[4096];
        n=read(sockfd,inbuffer,sizeof(inbuffer));
        if(n>0)
        {
            inbuffer[n]=0;
            std::cout<<inbuffer<<std::endl;
        }
        close(sockfd);
    }
    return 0;
}